package com.settlement.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.base.IBaseEnum;
import com.settlement.system.common.enums.EmailStatusEnum;
import com.settlement.system.common.enums.RegisterEmailStatusEnum;
import com.settlement.system.common.exception.BusinessException;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.controller.AmazonContext;
import com.settlement.system.mapper.SysEmailMapper;
import com.settlement.system.model.entity.SysAmazon;
import com.settlement.system.model.entity.SysEmail;
import com.settlement.system.model.form.SysEmailForm;
import com.settlement.system.model.query.SysEmailQuery;
import com.settlement.system.model.vo.RegisterEmailVo;
import com.settlement.system.model.vo.SysEmailImportVo;
import com.settlement.system.service.SysAmazonService;
import com.settlement.system.service.SysEmailService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 邮箱表 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2024-07-17
 */
@Service
@RequiredArgsConstructor
public class SysEmailServiceImpl extends ServiceImpl<SysEmailMapper, SysEmail> implements SysEmailService {

    private final SysAmazonService amazonService;

    @Override
    public Page<SysEmail> getPage(SysEmailQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 查询数据
        Page<SysEmail> page = new Page<>(pageNum, pageSize);
        Page<SysEmail> mapperPage = this.baseMapper.getPage(page, queryParams);
        for (SysEmail record : mapperPage.getRecords()) {
            record.setStatusName(IBaseEnum.getLabelByValue(record.getStatus(), EmailStatusEnum.class));
        }
        return mapperPage;
    }

    @Override
    public boolean saveSysEmail(SysEmailForm sysEmailForm) {
        SysEmail sysEmail = new SysEmail();
        BeanUtils.copyProperties(sysEmailForm, sysEmail);
        sysEmail.setCreateTime(null);
        return this.saveOrUpdate(sysEmail);
    }

    @Override
    public SysEmailForm getSysEmailFormData(Long id) {
        SysEmail sysEmail = this.getById(id);
        SysEmailForm sysEmailForm = new SysEmailForm();
        BeanUtils.copyProperties(sysEmail, sysEmailForm);
        return sysEmailForm;
    }

    @Override
    public boolean deleteSysEmail(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "删除的数据为空");
        List<Long> idArray = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(idArray);
    }

    @Override
    public void importData(List<SysEmailImportVo> voList) {
        List<String> emailList = voList.stream().map(SysEmailImportVo::getEmail).distinct().toList();
        List<SysEmail> sysEmails = this.list(new LambdaQueryWrapper<SysEmail>().in(SysEmail::getEmail, emailList));
        // 检查是否出现重复
        if (sysEmails.size() > 0) {
            for (SysEmailImportVo sysEmailImportVo : voList) {
                sysEmailImportVo.setEmail(sysEmailImportVo.getEmail().strip());
                if (sysEmails.stream().anyMatch(sysEmail -> Objects.equals(sysEmail.getEmail(), sysEmailImportVo.getEmail()))) {
                    throw new RuntimeException("邮箱【%s】已经存在，不允许重复导入".formatted(sysEmailImportVo.getEmail()));
                }
            }
        }
        List<SysEmail> sysEmailList = new ArrayList<>();
        for (SysEmailImportVo importVo : voList) {
            SysEmail sysEmail = new SysEmail();
            sysEmail.setEmail(importVo.getEmail().strip());
            sysEmail.setFirstName(importVo.getFirstName());
            sysEmail.setLastName(importVo.getLastName());
            sysEmail.setYearStr(importVo.getYearStr());
            sysEmail.setMonthStr(importVo.getMonthStr());
            sysEmail.setDayStr(importVo.getDayStr());
            sysEmailList.add(sysEmail);
        }
        this.saveOrUpdateBatch(sysEmailList);
    }

    @Override
    public List<SysEmailImportVo> findByIds(String idsStr) {
        if (!StringUtils.hasText(idsStr)) {
            return new ArrayList<>();
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysEmail> sysEmailList = this.getBaseMapper().selectBatchIds(ids);
        List<SysEmailImportVo> voList = new ArrayList<>();
        for (SysEmail sysEmail : sysEmailList) {
            SysEmailImportVo vo = new SysEmailImportVo();
            BeanUtils.copyProperties(sysEmail, vo);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public void register(String idsStr) {
        if (!StringUtils.hasText(idsStr)) {
            return;
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).toList();
        List<SysEmail> sysEmailList = this.getBaseMapper().selectBatchIds(ids);
        // 判断状态
        for (SysEmail sysEmail : sysEmailList) {
            if (!Objects.equals(sysEmail.getStatus(), EmailStatusEnum.UN_REGISTER.getValue()) && !Objects.equals(sysEmail.getStatus(), EmailStatusEnum.FAILED.getValue())) {
                throw new RuntimeException("邮箱【%s】状态不是【待注册】或者【注册失败】".formatted(sysEmail.getEmail()));
            }
        }
        // 加到任务列表
        RegisterEmailVo emailVo;
        for (SysEmail sysEmail : sysEmailList) {
            sysEmail.setStatus(EmailStatusEnum.REGISTERING.getValue());
            // 设置密码
            sysEmail.setPassword(StringUtils.randomString(10));
            emailVo = new RegisterEmailVo();
            emailVo.setEmail(sysEmail.getEmail());
            emailVo.setStatus(RegisterEmailStatusEnum.WAITING.getValue());
            AmazonContext.REGISTER_EMAIL_QUEUE.add(emailVo);
        }
        this.updateBatchById(sysEmailList);
    }

    @Override
    public List<SysEmail> getEmailMissions() {
        List<RegisterEmailVo> emailVos = new ArrayList<>();
        if (!AmazonContext.REGISTER_EMAIL_QUEUE.isEmpty()) {
            for (RegisterEmailVo emailVo : AmazonContext.REGISTER_EMAIL_QUEUE) {
                emailVos.add(emailVo);
                if (emailVos.size() >= 50) {
                    break;
                }
            }
        }
        // 获取前50条记录
        if (emailVos.size() == 0) {
            return new ArrayList<>();
        }
        List<String> emailList = emailVos.stream().map(RegisterEmailVo::getEmail).distinct().toList();
        return this.list(new LambdaQueryWrapper<SysEmail>().in(SysEmail::getEmail, emailList));
    }

    @Override
    public boolean updateStatus(List<SysEmailForm> sysEmailFormList) {
        List<String> emailList = sysEmailFormList.stream().map(SysEmailForm::getEmail).distinct().toList();
        List<SysEmail> sysEmailList = this.list(new LambdaQueryWrapper<SysEmail>().in(SysEmail::getEmail, emailList));
        SysEmail sysEmail;
        for (SysEmailForm sysEmailForm : sysEmailFormList) {
            sysEmail = sysEmailList.stream().filter(sysEmail1 -> Objects.equals(sysEmail1.getEmail(), sysEmailForm.getEmail())).findFirst().orElse(null);
            if (Objects.nonNull(sysEmail)) {
                if (Objects.equals(sysEmailForm.getStatus(), 1)) {
                    sysEmail.setStatus(EmailStatusEnum.REGISTERED.getValue());
                } else {
                    sysEmail.setStatus(EmailStatusEnum.FAILED.getValue());
                }
            }
        }
        return this.updateBatchById(sysEmailList);
    }

    @Override
    public void transferAmazonAccount(String idsStr) {
        if (!StringUtils.hasText(idsStr)) {
            return;
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysEmail> sysEmailList = this.getBaseMapper().selectBatchIds(ids);
        for (SysEmail sysEmail : sysEmailList) {
            Assert.isTrue(Objects.equals(sysEmail.getStatus(), EmailStatusEnum.REGISTERED.getValue()), "邮箱【%s】状态不是【注册成功】，请先注册邮箱".formatted(sysEmail.getEmail()));
        }
        List<String> emailList = sysEmailList.stream().map(SysEmail::getEmail).distinct().toList();
        List<SysAmazon> sysAmazons = amazonService.list(new LambdaQueryWrapper<SysAmazon>().in(SysAmazon::getEmail, emailList));
        if (sysAmazons.size() > 0) {
            throw new BusinessException("邮箱【%s】已经转换过亚马逊账号，请勿重复转换".formatted(sysAmazons.get(0).getEmail()));
        }
        SysAmazon amazon;
        List<SysAmazon> amazonList = new ArrayList<>();
        for (SysEmail sysEmail : sysEmailList) {
            amazon = sysAmazons.stream().filter(sysAmazon -> Objects.equals(sysAmazon.getEmail(), sysEmail.getEmail())).findFirst().orElse(null);
            if (Objects.isNull(amazon)) {
                amazon = new SysAmazon();
                amazon.setEmail(sysEmail.getEmail());
                amazon.setPassword(sysEmail.getPassword());
                amazonList.add(amazon);
            }
        }
        if (amazonList.size() > 0) {
            amazonService.saveBatch(amazonList);
        }
    }
}
